//
//  NetworkTools.swift
//  weiBo
//
//  Created by mac on 15/12/10.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking

/// HTTP 请求方法枚举
enum HMRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// MARK: - 网络工具
class NetworkTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    private let appKey = "1819594900"
    private let appSecret = "ec04b40ef46c9df46139f5147b31db72"
    private let redirectUrl = "http://www.baidu.com"
    
    //网络请求完成回调,类似于 OC 的 typeDefine
    typealias HMRequestCallBack = (result: AnyObject?, error: NSError?)->()

    // 单例
    static  let sharedTools: NetworkTools = {
        /// OAuth 授权 URL
        let tools = NetworkTools(baseURL: nil)
        
        //设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转化成 set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
}

//MARK: - OAuth 方法
extension NetworkTools {
    
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        return NSURL(string: urlString)!
    }
    
    //加载 AccessToken
    func loadAccessToken(code:String, finished: HMRequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret":appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
    }
}

// MARK: - 封装 AFN 网络方法
extension NetworkTools {
    /**
     网络请求
     
     - parameter method:     GET / POST
     - parameter URLString:  URLString
     - parameter parameters: 参数字典
     - parameter finished:   完成回调
     */
    private func request(method:HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        //定义成功回调
        let success = { (task: NSURLSessionDataTask?, result: AnyObject) -> Void in
            finished(result: result, error: nil)
            
        }
        
        //定义失败回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == HMRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
}
